package com.googlecode.droidircclient;

import java.io.*;
import java.util.Vector;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.content.Context;
import android.view.KeyEvent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.os.Handler;
import android.view.View;
import android.view.Menu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.googlecode.droidircclient.Sockets.*;

public class DroidIRCClientActivity extends Activity {	
	private ViewScroller output;
	private EditText input;
	private ClientSocket sock;
	private Vector<String> history = new Vector<String>();
	private int inHistory = 0;
	private ScrollView scroll;
	private Handler handler;
	private Thread thread;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);      
        setContentView(R.layout.main);
        // Find basic input/output - we will have to modify these routines a bit
        // when we support multiple connections/rooms even
        output  = (ViewScroller)findViewById(R.id.flipper);
        getCurrentView().setName("server");
    	input   = (EditText)findViewById(R.id.input);
    	scroll  = (ScrollView)findViewById(R.id.scrollView1);
    	thread  = null;

    	/* Fun little thread attempt */
        handler = new Handler();
        //Thread t = new ReaderThread(sock, handler, this);
        //t.start(); // This will read things to LogCat system out
    }//onCreate
    
    /**
     * Override to display settings menu
     * 
     * Let me recommend some good reading material :)
     * http://developer.android.com/guide/topics/ui/menus.html
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
    	Intent prefsInt = new Intent(getApplicationContext(), GeneralPreferencesActivity.class);
    	Intent servInt  = new Intent(getApplicationContext(), ServerInfoActivity.class);
    	
    	// Inflate the menu so we can see things
    	inflater.inflate(R.menu.general_menu, menu);
    	
    	// Now update for certain menus
    	MenuItem prefs = menu.findItem(R.id.profile);
    	MenuItem serv  = menu.findItem(R.id.servers);
    	prefs.setIntent(prefsInt);
    	serv.setIntent(servInt);
    	return true;
    }
    
    //Manage menu clicks
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
    	SharedPreferences prefs = getSharedPreferences(".droidIRC", MODE_PRIVATE);
    	switch(item.getItemId()){
    		case R.id.profile:
        		startActivity(item.getIntent());
        		return true;
    		case R.id.servers:
    			Intent intender = item.getIntent();
    			if(intender == null){
    				updateOutput("Tried to open \"Server\" menu, but null intent");
    				System.out.println("Tried to open \"Server\" menu, but null intent");
    			}
    			else startActivity(intender);
    			return true;
    		case R.id.connect: // Currently only supporting single server connections
    			String host = prefs.getString("server", "");
    			int port    = prefs.getInt("port", 6667);
    			
    			if(port < 0 || host.length() <= 0)
    				return true;
    			
    			if(thread != null) {
    				sock.write("PING :dying\n");
    				sock.close();
    				try{
    					thread.join();
    				}
    				catch(InterruptedException e){
    					
    				}
    			}
    			updateOutput("Attempting to connect to " + host + " at port " + port + '\n');
    			try {
    				sock = new ClientSocket(host, port);
    			} catch(IOException e) {
    				System.err.println("Error: "+e.toString()+"\n");
    				return true;
    			}

    			input.setOnKeyListener(new InputKeyListener(input, output, sock, this));
    			thread = new ReaderThread(sock, handler, prefs, this);
    			thread.start();
    			return true;
    	}//menu switch
	
    	return true;
    }

    //manage history scroll buttons
    public void history_up(View view){
    	if(inHistory-1 >= 0){
    		input.setText(history.elementAt(--inHistory));
    	}
    }
    public void history_down(View view){
    	if(inHistory+1 < history.size()){
    		input.setText(history.elementAt(++inHistory));
    	}
    }

    /**
     * Clean up
     */
    @Override
    public void onDestroy() {
    	if(sock != null && sock.isValid())
    		sock.close();
    	super.onDestroy(); // Avoid crashing - clean up properly still
    }
    
    public int findView(String name){
    	ScrollView temp = null;
    	IRCView stud = null;
    	int j;
		for(j = 0;j<output.getChildCount();++j){
    		System.out.println("j = " + j + "/" + output.getChildCount());
    		temp = (ScrollView)output.getChildAt(j);
    		stud = (IRCView)temp.getChildAt(0);
    		if(stud.getName().equals(name)) break;
    	}
    	if(stud == null){
    		System.out.println("Id " + name + "not found among current views.");
    		return -1;
    	}	
    	return j;
    }
    
    
    
    /**
     * @param name
     * setNewView
     * Use this method to add a new view to the ViewScroller, i.e. when we join a new channel.
     */
    void setNewView(String name){
    	int j = findView(name);
    	//if(j >= 0) return;//view already exists
    	LayoutInflater stu = getLayoutInflater();
		View template = stu.inflate(R.layout.template, output,false);
		System.out.println("template = " + template);
		LayoutParams params = template.getLayoutParams();
		ScrollView newview = new ScrollView(this);
		IRCView chanwin = new IRCView(this);
		chanwin.setName(name);
		System.out.println("New window's name is |" + name + "|");
		chanwin.setBackgroundColor(0xffffffff);
		chanwin.setTextColor(0xff000000);
		newview.addView(chanwin);
    	output.addView(newview, output.getChildCount(),params);
    	output.setDisplayedChild(output.getChildCount()-1);
    	System.out.println("Added view with name " + name);
    }
    /**
     * removeCurrentView
     * removes the view currently being displayed.
     */
    public void removeCurrentView(){
    	output.removeViewAt(output.getDisplayedChild());
    }

    public void removeViewAt(int target){
		output.removeViewAt(target);
    }

    
    /**
     * removeView
     * removes the view with the provided name 
     */
    public void removeView(String name){
    	int j = findView(name);    	
    	if(j>=0)output.removeViewAt(j);
    }
    
    /**
     * getCurrentView
     * This method returns the TextView that is currently being displayed by the ViewScroller "output."
     */
    public IRCView getCurrentView(){
    	ScrollView rent = (ScrollView)output.getCurrentView();
    	IRCView kid = (IRCView)rent.getChildAt(0);
    	return kid;
    }
    
    public String getCurrentViewName(){
    	ScrollView rent = (ScrollView)output.getCurrentView();
    	IRCView kid = (IRCView)rent.getChildAt(0);
    	return kid.getName();
    }        
    
    public int findViewNameAt(String name){
    	ScrollView temp = null;
    	IRCView stud = null;
    	int j;
		
    	for(j = 0;j<output.getChildCount();++j){
    		System.out.println("j = " + j + "/" + output.getChildCount());
    		temp = (ScrollView)output.getChildAt(j);
    		stud = (IRCView)temp.getChildAt(0);
    		if(stud.getName().equals(name)) break;
    	}
    	if(stud == null){
    		System.out.println("Id " + name + "not found among current views.");
    		return -1;
    	}	
    	return j;
    }
    
    /**
     * updateOutput
     * Method updates the output window (can only update UI from UI thread)
     * 
     */
    public void updateOutput(String text) {//current view
    	getCurrentView().append(text);
    }
    public void updateOutput(String text,String id) {//target view
    	int j = findView(id);    	
    	if(j>=0){
    		ScrollView temp = (ScrollView)output.getChildAt(j);
    		if (temp != null){
    			IRCView stud = (IRCView) temp.getChildAt(0);
    			stud.append(text);
    		}
    	}
    }
    
    /**
     * updateScroll
     * Jump to bottom on message sent or received
     */
    public void updateScroll() {
    	scroll.post(new Runnable() {
    		@Override
    		public void run() {
    			scroll.smoothScrollTo(0, getCurrentView().getBottom());
    		}
    	});
    }
    /**
     * updateHistory
     * Add sent text to history
     */
    public void updateHistory(String addend) {
    	history.addElement(addend);
    	inHistory=history.size();
    }
}